<?php
/**
 * Description: 收藏上岸计划任务
 * User: devforma
 * Date: 15/1/7
 * Time: 14:02
 */

class CollectTask implements iController {

    private $userIdField, $userId;
    
    /**
     * api请求处理主函数
     * @param array $queryArgs 就是$_REQUEST变量
     * @return array api返回结果，必须含response_code
     */
    public function output($queryArgs) {
        global $uddb;
        
        //验证并确定求求用户的身份，为0表示验证失败，为1表示正式用户，为2表示游客
        $u = validateUser($queryArgs); 
        if ($u == 0 || empty($queryArgs['task_id']) || !is_numeric($queryArgs['task_id'])) {
            return genOutput(1000);
        }

        if ($u == 1) { //正式用户
            $this->userIdField = 'user_id';
            $this->userId = $queryArgs['user_id'];
        } elseif ($u == 2) { //游客身份
            $this->userIdField = 'guest_id';
            $this->userId = $queryArgs['guest_id'];
        } else {
            return genOutput(1000);
        }
        
        //获取任务记录
        $sql = "SELECT * FROM `{$uddb->recentMissionInfo}`
                WHERE `id`=:task_id AND `{$this->userIdField}`=:user";
        $task = $uddb->getRow($sql, array(
            ':task_id' => $queryArgs['task_id'],
            ':user' => $this->userId
        ));
        
        //recent表无记录则到history表中去找
        if (empty($task)) {
            $sql = "SELECT * FROM `{$uddb->historyMissionAction}`
                    WHERE `mission_id`=:task_id AND `{$this->userIdField}`=:user";
            $task = $uddb->getRow($sql, array(
                ':task_id' => $queryArgs['task_id'],
                ':user' => $this->userId
            ));
        }

        if (empty($task)) return genOutput(1000);
        
        $sql = "SELECT * FROM `{$uddb->collection}`
                WHERE `{$this->userIdField}`=:user AND `mission_id`=:task_id";
        $collectExists = $uddb->getRow($sql, array(':user'=>$this->userId,
                                                   ':task_id'=>$queryArgs['task_id'])
                                       );
        if (empty($collectExists)) { //未收藏过
            $uddb->insert($uddb->collection, array(
                "$this->userIdField" => $this->userId,
                'mission_id' => $queryArgs['task_id'],
                'mission_type' => $task->mission_type,
                'mission_title' => $task->mission_title,
                'mission_content_id' => $task->mission_content_id,
                'mission_content' => $task->mission_content
            ));
            return genOutput(1);
        } else { //已经收藏过
            return genOutput(2001);
        }

    }
}